package framework;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;

/**
 * Created by Administrator on 2017/9/28.
 * 索引操作
 */
public class IndexClient {

    @Autowired
    private static ConcurrentHashMap<String, Client> companyIpMap = new ConcurrentHashMap<String, Client>();

    private Logger log = LoggerFactory.getLogger(IndexClient.class);

    private EsClusterConfigProperties esClusterConfigProperties = new EsClusterConfigProperties();

    IndexClient(){};
    private Client getTest(){
        // 9300 是我们java 连接的esserver 的端口。9200 是restapi 的接口
        Settings settings = Settings.builder()
                .put("client.transport.sniff", true)
                .put("cluster.name", "test")
                .put("client.transport.ping_timeout", "1000s").build();
        Client client = null;

        //Settings settings =Settings.EMPTY;
        if(client == null){
            //PreBuiltTransportClient
            try {
                client = new PreBuiltTransportClient(settings)
                        .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            //  .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("host2"), 9300));
        }
        return client;
    }

    public Client getClient(){
        Client client = companyIpMap.get(esClusterConfigProperties.getClusterIp());
        if (client == null) {
            synchronized (IndexClient.class) {
                if (client == null) {
                    log.info("create client start!!!!");
                    client = getInnerClient();
                }
            }
        }
        return client;//getInnerClient();
    }

    /**
     * 传输客户端排除非数据节点的原因是为了避免将搜索流量发送到仅主节点。
     * 连接的都是数据节点
     * @return
     */
    private Client getInnerClient() {
        try {
            Settings settings = Settings.builder()
                    .put("client.transport.sniff", true)
                    .put("cluster.name", esClusterConfigProperties.getClusterName())
                    .build();

            TransportClient client = new PreBuiltTransportClient(settings);
            String[] ipArray = esClusterConfigProperties.getClusterIp().split(",");
            if (ipArray != null && ipArray.length > 0) {
                for (int i = 0; i < ipArray.length; i++) {
                    String[] temp = ipArray[i].split(":");
                    int port = Integer.parseInt(temp[1]);
                    if (temp != null && temp.length == 2) {
                        client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(temp[0]), port));
                    }
                }
                companyIpMap.put(esClusterConfigProperties.getClusterIp(), client);
                return client;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 创建索引
     * @param indexName
     */
    public  boolean createIndex(String indexName){
        CreateIndexResponse response = getClient().admin().indices().prepareCreate(indexName).get();
        return response.isAcknowledged();
    }

    /**
     * 删除索引
     * @param indexName
     */
    public  boolean delIndex(String indexName){
       DeleteIndexResponse response =  getClient().admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet();
        return  response.isAcknowledged();
    }


    /**
     * 判断索引是否存在
     * @param indexName
     * @return
     */
    public  boolean isIndexExists(String indexName) {
        IndicesExistsResponse indicesExistsReq = getClient().admin().indices().prepareExists(indexName).get();
        return indicesExistsReq.isExists();
    }

    /**
     * 判断表是否存在
     * @param indexName
     * @param typeName
     * @return
     * @throws InterruptedException
     * @throws java.util.concurrent.ExecutionException
     */
    public  boolean isTypeExists(String indexName, String typeName)
            throws InterruptedException, ExecutionException {
        TypesExistsResponse typeExist = getClient().admin()
                .indices().prepareTypesExists(indexName).setTypes(typeName).get();
        return typeExist.isExists();
    }

}
